//
// Created by 李孝威 on 2021/4/8.
//

#include "Observerable.h"

Observerable::Observerable() {};

Observerable::~Observerable() {}

void Observerable::Attach(Observer *pOb) {

    if (pOb == NULL) {
        return;
    }
    // 判断是否已经注册
    auto it = _Obs.begin();
    for (; it != _Obs.end(); it++) {
        if (*it == pOb) {
            return;
        }
    }

    _Obs.push_back(pOb);
}

void Observerable::Detach(Observer *pOb) {
    if ((pOb == NULL) || (_Obs.empty() == true)) {
        return;
    }

    _Obs.remove(pOb);
}

void Observerable::DetachAll() {
    _Obs.clear();
}

void Observerable::SetChange(string news) {
    _bChange = true;
    Notify(((void *) news.c_str()));
}

void Observerable::Notify(void *pArg) {
    if (_bChange == false) {
        return;
    }

    auto it = _Obs.begin();
    for (; it != _Obs.end(); it++) {
        (*it)->Update(pArg);
    }

    _bChange = false;
}

int Observerable::GetObserverCount() const {
    return _Obs.size();
}

void Observerable::GetSomeNews(string str) {
    SetChange(str);
}
